package server;

import mapper.Context;
import mapper.Host;
import mapper.Wrapper;

import java.io.InputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Map;

public class RequestProcessor extends Thread {

    private Socket socket;

    private Map<String, Host> hostMap;

    public RequestProcessor(Socket socket, Map<String, Host> hostMap) {
        this.socket = socket;
        this.hostMap = hostMap;
    }

    @Override
    public void run() {
        try{
            InputStream inputStream = socket.getInputStream();

            // 封装Request对象和Response对象
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());

            String url = request.getUrl(); //        /web_demo/demo
            int secondChar = url.indexOf("/", 1);
            String contextPath = "";
            String servletPath = "";
            if (secondChar != -1) {
                contextPath = url.substring(0, secondChar);//    /web_demo
                servletPath = url.substring(secondChar);//    /demo
            } else {
                contextPath = url;
            }

            InetAddress inetAddress = socket.getInetAddress();
            String hostName = inetAddress.getHostName(); // localhost

            Host host = hostMap.get("localhost");
            Context context = host.getContextMap().get(contextPath);
            Wrapper wrapper = null;
            Servlet servlet = null;
            if (context != null) {
                wrapper = context.getWrapperMap().get(servletPath);
                servlet = wrapper.getServlet();
            }

            // 静态资源处理
            if(servlet == null) {
                response.outputHtml(request.getUrl());
            }else{
                // 动态资源servlet请求
                servlet.service(request, response);
            }

            socket.close();

        }catch (Exception e) {
            e.printStackTrace();
        }

    }
}
